<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="报关单号" prop="declarationNo">
        <el-input
          v-model="queryParams.declarationNo"
          placeholder="请输入报关单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报关类型" prop="declarationType">
        <el-select v-model="queryParams.declarationType" placeholder="请选择报关类型" clearable>
          <el-option
            v-for="dict in dict.type.fiscale_declaration_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="贸易方式" prop="tradeMode">
        <el-select v-model="queryParams.tradeMode" placeholder="请选择贸易方式" clearable>
          <el-option
            v-for="dict in dict.type.fiscale_trade_mode"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="运输方式" prop="transportMode">
        <el-select v-model="queryParams.transportMode" placeholder="请选择运输方式" clearable>
          <el-option
            v-for="dict in dict.type.fiscale_transport_mode"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报关状态" prop="customsStatus">
        <el-select v-model="queryParams.customsStatus" placeholder="请选择报关状态" clearable>
          <el-option
            v-for="dict in dict.type.fiscale_customs_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出口日期" prop="exportDate">
        <el-date-picker clearable
          v-model="queryParams.exportDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择出口日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fiscale:declaration:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fiscale:declaration:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fiscale:declaration:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fiscale:declaration:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5" v-show="!multiple">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          :disabled="multiple"
          @click="handleSubmit"
          v-hasPermi="['fiscale:declaration:submit']"
        >提交</el-button>
      </el-col>
      <el-col :span="1.5" v-show="!multiple">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleApprove"
          v-hasPermi="['fiscale:declaration:approve']"
        >审批</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="declarationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报关单号" align="center" prop="declarationNo" />
      <el-table-column label="报关类型" align="center" prop="declarationType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_declaration_type" :value="scope.row.declarationType"/>
        </template>
      </el-table-column>
      <el-table-column label="贸易方式" align="center" prop="tradeMode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_trade_mode" :value="scope.row.tradeMode"/>
        </template>
      </el-table-column>
      <el-table-column label="运输方式" align="center" prop="transportMode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_transport_mode" :value="scope.row.transportMode"/>
        </template>
      </el-table-column>
      <el-table-column label="启运港" align="center" prop="departurePort" />
      <el-table-column label="目的港" align="center" prop="destinationPort" />
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="币种" align="center" prop="currency" />
      <el-table-column label="报关状态" align="center" prop="customsStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_customs_status" :value="scope.row.customsStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="出口日期" align="center" prop="exportDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.exportDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['fiscale:declaration:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fiscale:declaration:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fiscale:declaration:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报关单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="报关单号" prop="declarationNo">
          <el-input v-model="form.declarationNo" placeholder="请输入报关单号" />
        </el-form-item>
        <el-form-item label="报关类型" prop="declarationType">
          <el-select v-model="form.declarationType" placeholder="请选择报关类型">
            <el-option
              v-for="dict in dict.type.fiscale_declaration_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="贸易方式" prop="tradeMode">
          <el-select v-model="form.tradeMode" placeholder="请选择贸易方式">
            <el-option
              v-for="dict in dict.type.fiscale_trade_mode"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运输方式" prop="transportMode">
          <el-select v-model="form.transportMode" placeholder="请选择运输方式">
            <el-option
              v-for="dict in dict.type.fiscale_transport_mode"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启运港" prop="departurePort">
          <el-input v-model="form.departurePort" placeholder="请输入启运港" />
        </el-form-item>
        <el-form-item label="目的港" prop="destinationPort">
          <el-input v-model="form.destinationPort" placeholder="请输入目的港" />
        </el-form-item>
        <el-form-item label="出口日期" prop="exportDate">
          <el-date-picker clearable
            v-model="form.exportDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择出口日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="币种" prop="currency">
          <el-input v-model="form.currency" placeholder="请输入币种" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog title="审批报关单" :visible.sync="approveOpen" width="400px" append-to-body>
      <el-form ref="approveForm" :model="approveForm" :rules="approveRules" label-width="80px">
        <el-form-item label="审批结果" prop="customsStatus">
          <el-radio-group v-model="approveForm.customsStatus">
            <el-radio label="approved">审批通过</el-radio>
            <el-radio label="rejected">审批拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="报关员" prop="customsOfficer">
          <el-input v-model="approveForm.customsOfficer" placeholder="请输入报关员" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApprove">确 定</el-button>
        <el-button @click="cancelApprove">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeclaration, getDeclaration, delDeclaration, addDeclaration, updateDeclaration, submitDeclaration, approveDeclaration } from "@/api/fiscale/declaration";

export default {
  name: "Declaration",
  dicts: ['fiscale_declaration_type', 'fiscale_trade_mode', 'fiscale_transport_mode', 'fiscale_customs_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报关单管理表格数据
      declarationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示审批弹出层
      approveOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        declarationNo: null,
        declarationType: null,
        tradeMode: null,
        transportMode: null,
        customsStatus: null,
        exportDate: null,
      },
      // 表单参数
      form: {},
      // 审批表单参数
      approveForm: {},
      // 表单校验
      rules: {
        declarationNo: [
          { required: true, message: "报关单号不能为空", trigger: "blur" }
        ],
        declarationType: [
          { required: true, message: "报关类型不能为空", trigger: "change" }
        ],
        tradeMode: [
          { required: true, message: "贸易方式不能为空", trigger: "change" }
        ],
        transportMode: [
          { required: true, message: "运输方式不能为空", trigger: "change" }
        ],
      },
      // 审批表单校验
      approveRules: {
        customsStatus: [
          { required: true, message: "审批结果不能为空", trigger: "change" }
        ],
        customsOfficer: [
          { required: true, message: "报关员不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询报关单管理列表 */
    getList() {
      this.loading = true;
      listDeclaration(this.queryParams).then(response => {
        this.declarationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        declarationId: null,
        declarationNo: null,
        declarationType: null,
        tradeMode: null,
        transportMode: null,
        departurePort: null,
        destinationPort: null,
        exportDate: null,
        totalAmount: null,
        currency: null,
        totalWeight: null,
        totalPackages: null,
        customsStatus: null,
        submitDate: null,
        customsOfficer: null,
        customsCode: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.declarationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报关单管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const declarationId = row.declarationId || this.ids
      getDeclaration(declarationId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改报关单管理";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.$router.push({ path: '/fiscale/customs/declaration/detail', query: { declarationId: row.declarationId } });
    },
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.declarationId != null) {
            updateDeclaration(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeclaration(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const declarationIds = row.declarationId || this.ids;
      
      // 检查是否为草稿状态，只有草稿状态才能删除
      if (Array.isArray(declarationIds)) {
        // 批量删除
        for (let i = 0; i < declarationIds.length; i++) {
          const declaration = this.declarationList.find(item => item.declarationId === declarationIds[i]);
          if (declaration && declaration.customsStatus !== 'draft') {
            this.$modal.msgWarning("只有草稿状态的报关单才能删除，报关单号:" + declaration.declarationNo + " 状态:" + declaration.customsStatus);
            return;
          }
        }
      } else {
        // 单个删除
        const declaration = this.declarationList.find(item => item.declarationId === declarationIds);
        if (declaration && declaration.customsStatus !== 'draft') {
          this.$modal.msgWarning("只有草稿状态的报关单才能删除，报关单号:" + declaration.declarationNo + " 状态:" + declaration.customsStatus);
          return;
        }
      }
      
      this.$modal.confirm('是否确认删除报关单管理编号为"' + declarationIds + '"的数据项？').then(function() {
        return delDeclaration(declarationIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch((error) => {
        if (error && error.message) {
          this.$modal.msgError(error.message);
        } else {
          this.$modal.msgError("删除失败");
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fiscale/declaration/export', {
        ...this.queryParams
      }, `declaration_${new Date().getTime()}.xlsx`)
    },
    /** 提交按钮操作 */
    handleSubmit() {
      const declarationId = this.ids[0];
      this.$modal.confirm('是否确认提交该报关单？').then(function() {
        return submitDeclaration(declarationId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("提交成功");
      }).catch(() => {});
    },
    /** 审批按钮操作 */
    handleApprove() {
      this.approveForm = {
        declarationId: this.ids[0],
        customsStatus: '',
        customsOfficer: ''
      };
      this.approveOpen = true;
    },
    /** 提交审批 */
    submitApprove() {
      this.$refs["approveForm"].validate(valid => {
        if (valid) {
          approveDeclaration(this.approveForm).then(response => {
            this.$modal.msgSuccess("审批成功");
            this.approveOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 取消审批 */
    cancelApprove() {
      this.approveOpen = false;
      this.approveForm = {};
    }
  }
};
</script>